package com.adcc.foc.controller;

import com.adcc.foc.utils.ImageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by DYB on 2016/11/30.
 */
@Controller
public class ImageController {

    @RequestMapping(value = "/randomPic")
    public void createImg(HttpServletRequest request, HttpServletResponse response) {
        OutputStream os = null;
        try {
            Object[] objs = ImageUtil.createImage();
            HttpSession session = request.getSession();
            session.setAttribute("imgCode", objs[0]);
            BufferedImage image = (BufferedImage) objs[1];
            response.setContentType("image/png");
            os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
